/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ohos.openharmony_qsvideoplayer.slice;

import com.ohos.openharmony_qsvideoplayer.ResourceTable;

import java.util.ArrayList;
import java.util.List;

import com.ohos.openharmony_qsvideoplayer.listvideo.CallBack;
import com.ohos.openharmony_qsvideoplayer.listvideo.ListCalculator;
import com.ohos.openharmony_qsvideoplayer.listvideo.ListViewGetter;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.window.service.WindowManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import org.song.videoplayer.DemoQSVideoView;
import org.song.videoplayer.IVideoPlayer;
import org.song.videoplayer.PlayListener;
import org.song.videoplayer.media.HarmonyMedia;

public class ListVideoSlice extends AbilitySlice implements CallBack {

    private ListContainer listContainer;
    private List<String> data = new ArrayList<>();
    private DemoQSVideoView myDemoQSVideoView;
    ListCalculator calculator;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent((ResourceTable.Layout_activity_list_video));
        WindowManager.getInstance().getTopWindow().get().setTransparent(true);
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        for (int i = 0; i < 10; i++) {
            data.add("这是一个标题" + i + ",https://mos-vod-drcn.dbankcdn.cn/P_VT/video_injection/A91343E9D/v3/9AB0A7921049102362779584128/MP4Mix_H.264_1920x1080_6000_HEAAC1_PVC_NoCut.mp4");
        }
        SampleItemProvider sampleItemProvider = new SampleItemProvider(data, this);
        calculator = new ListCalculator(new ListViewGetter(listContainer), (CallBack) this);

        listContainer.setItemProvider(sampleItemProvider);

//        listContainer.setOnScrollListener(new AbsListView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(AbsListView view, int scrollState) {
//                this.newState = scrollState;
//                if (newState == RecyclerView.SCROLL_STATE_IDLE)
//                    calculator.onScrolled(300);
//            }
//
//            @Override
//            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//                calculator.onScrolling(newState);
//            }
//
//            int newState = 0;
//
//        });

    }


    //=======================以下生命周期控制=======================
    private boolean playFlag;//记录退出时播放状态 回来的时候继续播放
    private int position;//记录销毁时的进度 回来继续该进度播放
    private EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());

    @Override
    protected void onBackground() {
        super.onBackground();
        if (myDemoQSVideoView != null) {

            //暂停
            playFlag = myDemoQSVideoView.isPlaying();
            myDemoQSVideoView.pause();
        }
    }

    @Override
    public void onActive() {
        super.onActive();
        if (playFlag) {
            myDemoQSVideoView.play();
        }
        handler.removeTask(runnable);
        if (position > 0) {
            myDemoQSVideoView.seekTo(position);
            position = 0;
        }
        if (myDemoQSVideoView != null) {
            if (getDisplayOrientation() == 0) { //横屏
                myDemoQSVideoView.enterWindowFullscreen();
            } else {
                myDemoQSVideoView.quitWindowFullscreen();
            }
        }
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (myDemoQSVideoView.getCurrentState() != IVideoPlayer.STATE_AUTO_COMPLETE) {
                position = myDemoQSVideoView.getPosition();
            }
            myDemoQSVideoView.release();
        }
    };


    @Override
    public void activeOnScrolled(Component activeView, int position) {
        myDemoQSVideoView = (DemoQSVideoView) activeView.findComponentById(ResourceTable.Id_item_qs);
        if (myDemoQSVideoView != null)
            myDemoQSVideoView.play();
    }

    @Override
    public void activeOnScrolling(Component activeView, int position) {
        final DemoQSVideoView demoQSVideoView = (DemoQSVideoView) findComponentById(ResourceTable.Id_item_qs);
        if (demoQSVideoView != null)
            demoQSVideoView.releaseInThread();
    }

    @Override
    public void deactivate(Component currentView, int position) {

    }

    class SettingHolder {
        private DemoQSVideoView demoQSVideoView;

        SettingHolder(Component component) {
            demoQSVideoView = (DemoQSVideoView) component.findComponentById(ResourceTable.Id_item_qs);
        }
    }

    class SampleItemProvider extends BaseItemProvider {
        private List<String> list;
        private AbilitySlice slice;

        SampleItemProvider(List<String> list, AbilitySlice slice) {
            this.list = list;
            this.slice = slice;
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public String getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
            Component component;
            SettingHolder holder;
            if (convertComponent == null) {
                component = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_item_video, null, false);
                holder = new SettingHolder(component);
                component.setTag(holder);
            } else {
                component = convertComponent;
                holder = (SettingHolder) component.getTag();
            }

            String[] arr = list.get(position).split(",");
            holder.demoQSVideoView.setDecodeMedia(HarmonyMedia.class);
            holder.demoQSVideoView.bindAbilitySlice(ListVideoSlice.this);
            holder.demoQSVideoView.setUIWithStateAndMode();
            holder.demoQSVideoView.setUp(arr[1], arr[0]);
            holder.demoQSVideoView.openCache();
            holder.demoQSVideoView.getCoverImageView().setImageAndDecodeBounds(ResourceTable.Media_cover);

            holder.demoQSVideoView.setPlayListener(new PlayListener() {
                @Override
                public void onStatus(int status) {

                }

                @Override
                public void onMode(int mode) {

                }

                @Override
                public void onEvent(int what, Integer... extra) {
                    //此段非必要，如果开放下面注释代码， 则取消这里的判断的赋值。
                    if (myDemoQSVideoView == null) {
                        myDemoQSVideoView = holder.demoQSVideoView;
                    }
//                    if (what == IVideoPlayer.EVENT_PREPARE_START) {
//                        //ConfigManage.releaseOther(qsVideoView);
//                        calculator.setCurrentActiveItem(position);
//                    }
                }
            });

            return component;
        }

    }

    @Override
    public void onBackPressed() {
        if (myDemoQSVideoView != null && myDemoQSVideoView.onBackPressed()) {
            myDemoQSVideoView.release();
            handler.removeTask(runnable);
        }
        super.onBackPressed();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (myDemoQSVideoView != null) {
            myDemoQSVideoView.release();
            handler.removeTask(runnable);
        }
    }
}
